package tool;

import org.apache.struts2.util.StrutsTypeConverter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.Objects;

public class DateTypeConverter extends StrutsTypeConverter {
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @SuppressWarnings("rawtypes")
    @Override
    public java.sql.Date convertFromString(Map map, String[] strings, Class aClass) {
        try {
            String text = strings[0];
            if (Objects.nonNull(text) && text.length() > 0) {
                java.util.Date date = dateFormat.parse(text);
                if (Objects.nonNull(date)) {
                    return new java.sql.Date(date.getTime());
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String convertToString(@SuppressWarnings("rawtypes") Map map, Object o) {
        if (Objects.nonNull(o)) {
            return dateFormat.format(o);
        }
        return "";
    }
}
